#include "TextResExtractor.h"

int GetEncodeOffset(EncodeKind k)
{	
	switch(k)
	{
	case ANSI_ENCODE: return 0;
	case UTF8_ENCODE: return 3;
	case UTF16_Little_Endian: return 2;
	case UTF32_Little_Endian: return 4;
	case UTF16_Big_Endian: return 2;
	case UTF32_Big_Endian: return 4;
	default:
		printf("GetEncodeOffset error: Unknow encode.\n");
		return 0;
	}
}

EncodeKind TextResExtractor::GetTextFileEncodeType(Res *res)
{
	unsigned char head[4];
	EncodeKind ekind = ANSI_ENCODE;;
	for(int i = 0; i < 4; ++i)
		head[i] = *((char*)res->data + i * sizeof(char));
	if(head[0] == 0xEF && head[1] == 0xBB && head[2] == 0xBF)
		ekind = UTF8_ENCODE;
	if(head[0] == 0xFF && head[1] == 0xFE)
	{
		if(head[2] != 0x00)
			ekind = UTF16_Little_Endian;
		else
			if(head[3] == 0x00)
				ekind = UTF32_Little_Endian;
	}
	if(head[0] == 0x00 && head[1] == 0x00&& head[2] == 0xFE && head[2] == 0xFF)
		ekind = UTF32_Big_Endian;
	if(head[0] == 0xFE && head[1] == 0xFF)
		ekind = UTF16_Big_Endian;
	return ekind;
}


void TextResExtractor::ExtractTextFile(Res *res, unsigned char * &buf, int* bufsize)
{
	EncodeKind k = GetTextFileEncodeType(res);
	int offset = GetEncodeOffset(k);
	if(buf == 0)
	{
		buf = new unsigned char[res->size - offset + 1];
	}
	memcpy(buf,(void*)((char*)res->data + offset * sizeof(char)),res->size - offset);
	buf[res->size - offset] ='\0';
	buf = (unsigned char*)buf;
	*bufsize = res->size - offset;
}


SINGLETON_OUTER_DECLARE(TextResExtractor)